﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NextCMS.Models;
using System.Web;
using System.Xml.Linq;

namespace NextCMS.DataAccess.XMLDataAccess
{
    internal class PageForms : IPageForm
    {
        private string FilePath = HttpContext.Current.Server.MapPath("~") + "/App_Data/Modules/PageForms.xml";
        XDocument doc = null;
        public PageForms()
        {
            doc = XDocument.Load(FilePath);  //load the xml file.
        }
        public T GetById<T>(int id)
        {

            var q = from d in doc.Descendants("PageForm")
                    where (int)d.Element("Id") == id
                    select d;

            PageContactUsFormModel contactForm = new PageContactUsFormModel();
            if (typeof(T).Name == contactForm.GetType().Name)
            {
                return (T)(object)contactForm.GetById(q.FirstOrDefault());
            }
            return default(T);
        }
        public List<T> GetAll<T>()
        {

            var q = from d in doc.Descendants("PageForm")
                    select d;
            List<T> lst = new List<T>();
            PageContactUsFormModel contactForm = new PageContactUsFormModel();
            if (typeof(T).Name == contactForm.GetType().Name)
            {
                foreach (var l in contactForm.GetAll(q))
                {
                    lst.Add((T)(object)l);
                }
            }
            return lst;
        }

        public int Save(IForm page)
        {

            var q = from d in doc.Descendants("PageForm")
                    select new PageFormModel
                    {
                        Id = (int)d.Element("Id"),

                    };
            int nextId = 0;
            if (q.Count() > 0)
                nextId = q.Max(s => s.Id) + 1;
            else
                nextId = 1;
            page.Id = nextId;
            var oMember = page.SaveElement(page);

            doc.Root.Add(oMember);
            doc.Save(FilePath);
            return nextId;
        }
        // Delete Record
        public void Delete(int id)
        {

            doc.Root.Elements("PageForm").Where(i => (int)i.Element("Id") == id).Remove();
            doc.Save(FilePath);
        }

        // Edit Record
        public void Edit(IForm page)
        {

            XElement node = doc.Root.Elements("PageForm").Where(i => (int)i.Element("Id") == page.Id).FirstOrDefault();
            node = page.EditElement(page, node);
            doc.Save(FilePath);
        }

        public void Dispose()
        {
            doc = null;
        }
    }
}
